<template>
  <div>
    <el-form-item label="相关知识点">
      <draggable :disabled="readonly" v-model="knowledgePoints" style="display: inline-block"
        @update="$emit('update-sort')">
        <el-tag v-for="knowledgePoint in knowledgePoints" :key="knowledgePoint.id" :closable="!readonly"
          @close="handleClose(knowledgePoint)">{{ knowledgePoint.name }}</el-tag>
      </draggable>
      <el-button v-if="!readonly" class="button-new-tag" size="small" @click="open()">+ New</el-button>
    </el-form-item>

    <!-- 知识点选择弹窗 -->
    <el-dialog :visible="dialogFormVisible" title="知识点" width="25%" :before-close="beforeClose">
      <el-form :model="knowledgePointQuery" label-position="left" label-width="80px" class="knowledgePointForm">
        <el-form-item label="知识点">
          <el-cascader ref="point" v-if="dialogFormVisible" v-model="point" :options="knowledgePointOptions"
            placeholder="请选择知识点" clearable />
          <el-button type="primary" @click="addKnowledgePoint(1)">添加</el-button>
          <el-button type="success" @click="aiJudgeKnowledgePoint" style="margin-left: 10px;">AI判断知识点</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" />
    </el-dialog>

    <!-- AI判断知识点弹窗 -->
    <el-dialog :visible.sync="aiKnowledgeDialogVisible" title="AI判断知识点" width="50%" :before-close="closeAiKnowledgeDialog">
      <div v-loading="aiKnowledgeLoading">
        <div v-if="aiKnowledgeResult && aiKnowledgeResult.length > 0">
          <h4>AI推荐的知识点：</h4>
          <div class="ai-knowledge-content">
            <el-checkbox-group v-model="selectedKnowledgePoints">
              <div v-for="(item, index) in aiKnowledgeResult" :key="index" class="knowledge-item">
                <el-checkbox :label="item.pointId" :value="item.pointId">
                  <span class="knowledge-name">{{ item.name }}</span>
                  <span class="knowledge-confidence" v-if="item.confidence">(置信度: {{ item.confidence }}%)</span>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
        <div v-else-if="!aiKnowledgeLoading">
          <el-empty description="未能找到知识点"></el-empty>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAiKnowledgeDialog">取 消</el-button>
        <el-button type="primary" @click="adoptAiKnowledge" :disabled="selectedKnowledgePoints.length === 0">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import { aiJudgeKnowledge, knowledgePointExceedLimit } from "@/api/point.js";

export default {
  name: "KnowledgePointManager",
  components: {
    draggable
  },
  props: {
    knowledgePoints: {
      type: Array,
      default: () => []
    },
    readonly: {
      type: Boolean,
      default: false
    },
    knowledgePointOptions: {
      type: Array,
      default: () => []
    },
    question: {
      type: Object,
      required: true
    },
    parentQuestion: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      point: "",
      knowledgePointQuery: {},
      // AI判断知识点相关数据
      aiKnowledgeDialogVisible: false,
      aiKnowledgeLoading: false,
      aiKnowledgeResult: [],
      selectedKnowledgePoints: []
    };
  },
  methods: {
    open() {
      this.dialogFormVisible = true;
    },
    beforeClose() {
      this.dialogFormVisible = false;
      this.point = "";
    },
    handleClose(knowledgePoint) {
      this.$emit('remove-knowledge-point', knowledgePoint);
    },
    addKnowledgePoint(type) {
      if (!this.point) {
        this.$message.warning('请选择知识点');
        return;
      }
      
      const pointId = this.point[this.point.length - 1];
      const pointName = this.getPointName(pointId);
      
      if (!pointName) {
        this.$message.error('无法获取知识点名称');
        return;
      }
      
      // 检查是否已存在该知识点
      const exists = this.knowledgePoints.some(point => point.pointId === pointId);
      if (exists) {
        this.$message.warning('该知识点已存在');
        return;
      }
      
      const point = {
        pointId: pointId,
        name: pointName
      };
      
      // 检查知识点关联题目数量限制
      knowledgePointExceedLimit(point.pointId).then((res) => {
        if (res.data) {
          this.$message({
            message: `警告：知识点"${point.name}"已关联10道或10道以上题目，建议一个知识点不要关联超过10道题目`,
            type: 'warning',
            duration: 8000,
          });
        }
      });
      
      this.$emit('add-knowledge-point', point);
      this.point = "";
      this.$message.success('知识点添加成功');
    },
    getPointName(pointId) {
      // 递归查找知识点名称
      const findPoint = (options, id) => {
        for (const option of options) {
          if (option.value === id) {
            return option.label;
          }
          if (option.children) {
            const found = findPoint(option.children, id);
            if (found) return found;
          }
        }
        return null;
      };
      return findPoint(this.knowledgePointOptions, pointId);
    },
    // AI判断知识点
    aiJudgeKnowledgePoint() {
      if (!this.question.title && this.question.type !== '6') {
        this.$message.warning('请先填写题目内容');
        return;
      }
      
      if (this.question.type === '6' && !this.question.materials) {
        this.$message.warning('材料题请先填写材料内容');
        return;
      }
      
      this.aiKnowledgeDialogVisible = true;
      this.aiKnowledgeLoading = true;
      this.selectedKnowledgePoints = [];
      
      // 构建题目内容
      let questionContent = '';
      if (this.question.type === '6') {
        questionContent = (this.parentQuestion.materials || this.question.materials || '') + (this.question.title || '');
      } else {
        if (this.parentQuestion.materials) {
          questionContent = this.parentQuestion.materials + this.question.title;
        } else {
          questionContent = this.question.title;
        }
      }
      
      // 获取叶子节点知识点列表
      const leafKnowledgePoints = this.getLeafKnowledgePoints(this.knowledgePointOptions);
      
      if (!leafKnowledgePoints || leafKnowledgePoints.length === 0) {
        this.$message.warning('知识点列表为空，无法进行AI判断');
        this.aiKnowledgeLoading = false;
        this.aiKnowledgeDialogVisible = false;
        return;
      }
      
      this.callAiJudgeKnowledgeAPI(questionContent, JSON.stringify(leafKnowledgePoints));
    },
    // 获取知识点选项的叶子节点
    getLeafKnowledgePoints(options, result = []) {
      options.forEach(option => {
        if (!option.children || option.children.length === 0) {
          result.push({
            pointId: option.value,
            name: option.label
          });
        } else {
          this.getLeafKnowledgePoints(option.children, result);
        }
      });
      return result;
    },
    // 调用AI判断知识点API
    callAiJudgeKnowledgeAPI(questionContent, knowledgePoints) {
      aiJudgeKnowledge(questionContent, knowledgePoints)
        .then(res => {
          if (res.code == 0) {
            const knowledgeNameList = res.data || [];
            if (knowledgeNameList.length === 0) {
              this.$message.warning('未能找到相关知识点');
              this.aiKnowledgeDialogVisible = false;
              this.aiKnowledgeResult = [];
            } else {
              this.aiKnowledgeResult = this.convertNamesToKnowledgePoints(knowledgeNameList, JSON.parse(knowledgePoints));
            }
          } else {
            this.$message.error(res.msg || 'AI判断知识点失败');
            this.aiKnowledgeResult = [];
          }
        })
        .catch(err => {
          console.error('AI判断知识点出错:', err);
          this.$message.error('AI判断知识点服务异常，请稍后再试');
          this.aiKnowledgeResult = [];
        })
        .finally(() => {
          this.aiKnowledgeLoading = false;
        });
    },
    // 将知识点名称列表转换为包含pointId的对象数组
    convertNamesToKnowledgePoints(nameList, allKnowledgePoints) {
      const result = [];
      nameList.forEach(name => {
        const matchedPoint = allKnowledgePoints.find(point => point.name === name);
        if (matchedPoint) {
          result.push({
            pointId: matchedPoint.pointId,
            name: matchedPoint.name
          });
        } else {
          console.warn(`未找到知识点"${name}"对应的pointId`);
          result.push({
            pointId: `temp_${Date.now()}_${Math.random()}`,
            name: name
          });
        }
      });
      return result;
    },
    // 关闭AI判断知识点弹窗
    closeAiKnowledgeDialog() {
      this.aiKnowledgeDialogVisible = false;
      this.aiKnowledgeResult = [];
      this.selectedKnowledgePoints = [];
      this.dialogFormVisible = false;
    },
    // 采纳AI推荐的知识点
    adoptAiKnowledge() {
      if (this.selectedKnowledgePoints.length === 0) {
        this.$message.warning('请选择要添加的知识点');
        return;
      }
      
      this.selectedKnowledgePoints.forEach(pointId => {
        const knowledgePoint = this.aiKnowledgeResult.find(item => item.pointId === pointId);
        if (knowledgePoint) {
          const exists = this.knowledgePoints.some(point => point.pointId === pointId);
          if (!exists) {
            const point = {
              pointId: knowledgePoint.pointId,
              name: knowledgePoint.name
            };
            
            knowledgePointExceedLimit(point.pointId).then((res) => {
              if (res.data) {
                this.$message({
                  message: `警告：知识点"${point.name}"已关联10道或10道以上题目，建议一个知识点不要关联超过10道题目`,
                  type: 'warning',
                  duration: 8000,
                });
              }
            });
            
            this.$emit('add-knowledge-point', point);
          }
        }
      });
      
      this.$message.success(`已添加 ${this.selectedKnowledgePoints.length} 个知识点`);
      this.closeAiKnowledgeDialog();
    }
  }
};
</script>

<style scoped>
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.knowledgePointForm {
  margin-top: 20px;
}

.ai-knowledge-content {
  max-height: 300px;
  overflow-y: auto;
}

.knowledge-item {
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.knowledge-name {
  font-weight: bold;
  margin-right: 8px;
}

.knowledge-confidence {
  color: #909399;
  font-size: 12px;
}
</style>